'use strict';

const glob = require('glob');

let models = {};

function loadModels() {
  const ms = glob.sync('app/models/**/*.js', { absolute: true });
  const self = __filename.replace(/\\/g, '/');
  for (const m of ms) {
    if (m === self) continue;
    models = { ...models, ...require(m) };
  }
}

/**
 * 指定更新的字段
 * @param table
 * @param values
 */
function columnFilter(table, values) {
  if (!models[table]) return values;
  let result;
  if (Array.isArray(values)) {
    result = [];
    for (const v of values) {
      result.push(columnFilter(table, v));
    }
  } else {
    const columns = models[table];
    result = {};
    for (const c of columns) {
      if (values[c] !== undefined) result[c] = values[c];
    }
  }
  return result;
}

loadModels();

module.exports = columnFilter;
